import 'package:flutter_pink_app/net/base/response.dart';
import 'package:flutter_pink_app/net/base/request.dart';
import "../service/response.dart";
import '../base/adapter.dart';
import 'package:dio/dio.dart';
import '../base/error.dart';

class DioAdapter extends BaseAdapter {
  @override
  Future<BaseResponse<T>> send<T>(BaseRequest req) async {
    // 基础请求参数
    final reqOption = BaseOptions(
      headers: req.header,
      connectTimeout: 5000,
      sendTimeout: 3000,
      receiveTimeout: 3000,
    );
    // 新建dio实例
    Dio dioInstance = Dio(reqOption);
    // dio回复报文
    Response<Map<String, dynamic>> res;
    try {
      if (req.method == SupportMethods.GET) {
        res = await dioInstance.get(req.url);
      } else if (req.method == SupportMethods.DELETE) {
        res = await dioInstance.delete(req.url, data: req.queryParams);
      } else if (req.method == SupportMethods.POST) {
        res = await dioInstance.post(req.url, data: req.queryParams);
      }
      // 捕捉DIO的错误
    } on DioError catch (e) {
      print('dio请求时有意外发生了意外的错误');
      print(e.toString());
      print(StackTrace.current);
      // 抛出错误
      throwErr(e.response?.statusCode, e.message, e);
    }
    // 请求成功则序列化dio数据
    final ServiceResponse dioData = ServiceResponse.fromJson(res.data);
    // 根据序列化数据封装成基础回复类
    return BaseResponse(
        data: dioData?.data, statusCode: dioData.code, message: dioData.msg);
  }

  @override
  throwErr(int code, String message, dynamic data) {
    throw BaseNetworkError(code, message, data);
  }
}
